package cn.com.netedge.iot.frontend.biz.utils;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import cn.com.netedge.iot.model.notice.ParaConfigNoticeMsgModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.constants.Globals;
import cn.com.netedge.iot.common.dataobject.ResultBean;
import cn.com.netedge.iot.common.utils.DateUtil;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;
import cn.com.netedge.iot.model.task.TaskParaModel;
import cn.com.netedge.iot.protocol.dlms.enums.ExceptionDescEnum;

public class DeviceCmdUtil {
    private static final Logger logger = LoggerFactory.getLogger(MasterSystemServiceImpl.class);


    /**
     * 判断是否超时
     *
     * @param startTime
     * @param timeout   超时时间秒
     * @return
     */
    public static boolean isTimeOut(long startTime, int timeout) {
        long timeoutLong = (long) timeout * 1000;
        long curr = System.currentTimeMillis();
        return curr - startTime > timeoutLong;
    }

    public static synchronized String genCmdId(String deviceNumber,int deviceType) {
        if (StringUtil.isEmpty(deviceNumber)) {
            deviceNumber = "00000000";
        }
        String cmdid = CacheKeyConstants.KEY_DEVICE_CMD + deviceNumber + "_" + deviceType;
        cmdid += ":" + DateUtil.DateToLong14Str(new Date());// 当前时间14位
        cmdid += "_" + StringUtil.randomString(6);// 随机数6位
        return cmdid;
    }

    public static ResultBean callResult(String cmdId, String deviceNumber, int deviceType, int taskSize) {
        ResultBean result = new ResultBean();
         // 开始等待接受下发结果
        String log = "【参数下发】操作命令:" + cmdId + ";设备编码:" + deviceNumber;
        long startTime = System.currentTimeMillis();
        int timeout = Globals.TASK_TIME_OUT;
        try {
            while (true) {
                // 在超时范围内等待返回命令
                if (DeviceCmdUtil.isTimeOut(startTime, timeout)) {
                    break;
                }
                // 请求缓存下发结果
                long count = RedisUtil.llen(cmdId);
                if (count >= taskSize) {
                    logger.info("-----读到结果-----");
                    logger.info("{} -> 返回第 {} 个任务， 共 {} 个", log, count, taskSize);
                    List<TaskParaModel> taskParaModels = RedisUtil.range(cmdId, 0, 0, TaskParaModel.class);
                    result.setData(taskParaModels);
                    result.setSuccess(true);
                    RedisUtil.delete(cmdId);
                    FeBizCacheUtil.popTopTask(deviceNumber, deviceType, cmdId);
                    break;
                }
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            logger.error("下发异常 {}", log, e);
            Thread.currentThread().interrupt();
            result.setSuccess(false);
            result.setMsg("下发失败.");
            RedisUtil.delete(cmdId);
            FeBizCacheUtil.popTopTask(deviceNumber, deviceType, cmdId);
        } catch (Exception e) {
            logger.error("下发异常" + log, e);
            result.setSuccess(false);
            result.setMsg("下发失败.");
            RedisUtil.delete(cmdId);
            FeBizCacheUtil.popTopTask(deviceNumber, deviceType, cmdId);
        }
        return result;
    }

    public static void main(String[] args) {
        ParaConfigNoticeMsgModel model = new ParaConfigNoticeMsgModel();
        model.setParaId(88);
        System.out.println(JSON.toJSONString(model));
    }
}
